Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.IO
Imports System.Collections
Imports MyFramework
Imports System.Xml

Public Class ShoppingCartList
    Inherits System.Web.UI.Page

    Protected WithEvents header As StockReportHeader
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents lblInformation As System.Web.UI.WebControls.Label
    Protected WithEvents chkFullContainer As System.Web.UI.WebControls.CheckBox
    Protected WithEvents chkPartOrder As System.Web.UI.WebControls.CheckBox
    Protected WithEvents txtHalfPallet As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtExistingOrderVolume As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtOrderNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtQty20Cont As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtVolumeUnit20 As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtQty40Cont As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtVolumeUnit40 As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtQty40HiCube As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtVolumeUnit40HiCube As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtTotalVolumeAvailable As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtTotalWeightAvailable As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtTotalPrice As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtSelectVolumeTotal As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPercentFull As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtRemainVolume As System.Web.UI.WebControls.TextBox
    Protected WithEvents Textbox1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents Textbox2 As System.Web.UI.WebControls.TextBox
    Protected WithEvents Textbox3 As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnProceedOrder As System.Web.UI.WebControls.Button
    Protected WithEvents btnBackToIDS As System.Web.UI.WebControls.Button
    Protected WithEvents btnSaveYourList As System.Web.UI.WebControls.Button
    Protected WithEvents btnClearSavedList As System.Web.UI.WebControls.Button
    Protected WithEvents btnRecalculated As System.Web.UI.WebControls.Button
    Protected WithEvents dlShoppingList As System.Web.UI.WebControls.DataList
    Protected WithEvents lblTest As System.Web.UI.WebControls.Label
    Protected WithEvents rdFullContainer As System.Web.UI.WebControls.RadioButton
    Protected WithEvents rdPartOrder As System.Web.UI.WebControls.RadioButton
    Protected WithEvents radHalfPallet As System.Web.UI.WebControls.RadioButton
    Protected WithEvents hidMeasUnit As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hidRoadWeight As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hid20C As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hid40C As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hid40HC As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents lblTerritory As System.Web.UI.WebControls.Label
    Protected WithEvents lblCountry As System.Web.UI.WebControls.Label
    Protected WithEvents lnkBackToIDS As System.Web.UI.WebControls.LinkButton
    Protected WithEvents ddlCountry As System.Web.UI.WebControls.DropDownList
    Protected lblToTalValue As System.Web.UI.WebControls.Label
    Protected WithEvents loggedInSection As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected divChangeConPoint As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected lblEmail As System.Web.UI.WebControls.Label
    Protected lblConsolidationText As System.Web.UI.WebControls.Label
    Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents lnkNotUseSignedInAccount As System.Web.UI.WebControls.LinkButton

    Private Const ONE_VOLUME_CBM_TO_CUFT As Double = 35.314
    Protected WithEvents txtTotalGoodWeight As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtGoodWeightPercentFull As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtGoodWeightRemain As System.Web.UI.WebControls.TextBox
    Private Const ONE_KG_TO_LBS As Double = 2.204

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Property SelectedCountry() As Country
        Get
            Try
                If Viewstate("SelectedCountry") Is Nothing Then
                    Viewstate("SelectedCountry") = CountryService.GetCountry(RequestContext.CurrentUser.CountryID)
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("SelectedCountry") Is Nothing Then
                Return CType(Viewstate("SelectedCountry"), Country)
            Else
                Return Nothing
            End If
        End Get
        Set(ByVal Value As Country)
            Viewstate("SelectedCountry") = Value
        End Set
    End Property

    Private ReadOnly Property Countries() As CountryCollection
        Get
            Try
                If Viewstate("Countries") Is Nothing Then
                    Viewstate("Countries") = CountryService.GetCountries(CountryColumns.CountryName, OrderDirection.ASC, True)
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("Countries") Is Nothing Then
                Return CType(Viewstate("Countries"), CountryCollection)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Private ReadOnly Property UnitSettingList() As UnitSettingCollection
        Get
            Try
                If (Viewstate("UnitSettingList") Is Nothing) Then
                    Viewstate("UnitSettingList") = UnitSettingService.GetUnitSettings()
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("UnitSettingList") Is Nothing Then
                Return CType(Viewstate("UnitSettingList"), UnitSettingCollection)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Private ReadOnly Property UnitSettingsOnlyByConPoint() As UnitSettingCollection
        Get
            Try
                If (Viewstate("UnitSettingsOnlyByConPoint") Is Nothing) Then
                    Viewstate("UnitSettingsOnlyByConPoint") = UnitSettingService.GetUnitSettingsOnlyByConPoint(ShoppingConext.ShopingSelectedConsolidation)
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("UnitSettingsOnlyByConPoint") Is Nothing Then
                Return CType(Viewstate("UnitSettingsOnlyByConPoint"), UnitSettingCollection)
            Else
                Return Nothing
            End If
        End Get
    End Property


    Private Function GetCBMValue(ByVal unitSettingID As Integer, ByVal minQtyVolume As Decimal) As Decimal
        Dim result As Decimal = 0
        If (minQtyVolume = 0 Or minQtyVolume = Nulls.NullDecimal) Then
            Dim cbmValue As Decimal = 0
            If (Not UnitSettingList Is Nothing AndAlso unitSettingID > 0) Then
                For i As Integer = 0 To UnitSettingList.Count - 1
                    If (UnitSettingList(i).UnitSettingID = unitSettingID) Then
                        cbmValue = UnitSettingList(i).CbmValue
                        For Each item As UnitSetting In UnitSettingsOnlyByConPoint
                            If (unitSettingID = item.UnitSettingID) Then
                                cbmValue = item.CbmValue
                                Exit For
                            End If
                        Next
                        Dim convertedUnit As Decimal = 1
                        If (IsImperialUnit) Then
                            convertedUnit = Convert.ToDecimal(ONE_VOLUME_CBM_TO_CUFT)
                        End If
                        Return cbmValue * convertedUnit
                    End If
                Next
            End If
        Else
            result = minQtyVolume
        End If
        Return result
    End Function

    Public Function GetCBMValueByUnitCode(ByVal unitCode As String) As Decimal
        Dim result As Decimal = 0

        If (Not UnitSettingList Is Nothing AndAlso unitCode > "") Then
            For i As Integer = 0 To UnitSettingList.Count - 1
                If (UnitSettingList(i).UnitCode = unitCode) Then
                    Dim convertedUnit As Decimal = 1
                    If (IsImperialUnit) Then
                        convertedUnit = Convert.ToDecimal(ONE_VOLUME_CBM_TO_CUFT)
                    End If
                    Return UnitSettingList(i).CbmValue * convertedUnit
                End If
            Next
        End If
        Return result
    End Function

    Private Sub LoadRoadWeightAndUnit()
        If (Not SelectedCountry Is Nothing) Then
            Select Case SelectedCountry.CountryCode
                Case "USA"
                    hidMeasUnit.Value = "cu ft"
                Case Else
                    hidMeasUnit.Value = "cbm"
                    'Todo: review later
                    'Case "UK", "ES", "ITA", "NZ", "NO", "TKY"
                    '    hidMeasUnit.Value = "cbm"
                    'Case Else
                    '    hidMeasUnit.Value = "m3"
            End Select
            Try
                ddlCountry.Items.FindByValue(SelectedCountry.CountryID.ToString()).Selected = True
            Catch ex As Exception
            End Try
            Dim roadWeight As Decimal = SelectedCountry.RoadWeight
            If (SelectedCountry.MeasUnit = "Imperial") Then
                roadWeight = SelectedCountry.RoadWeight * Convert.ToDecimal(ONE_KG_TO_LBS)
            End If
            If (roadWeight = Nulls.NullDecimal) Then
                hidRoadWeight.Value = "0"
            Else
                hidRoadWeight.Value = roadWeight.ToString()
            End If

        End If
    End Sub

    Protected Sub ddlCountry_OnSelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged
        SelectedCountry = CountryService.GetCountry(Convert.ToInt32(ddlCountry.SelectedValue))
        RequestContext.CurrentDestinationCountry = Convert.ToInt32(ddlCountry.SelectedValue)
        LoadRoadWeightAndUnit()
        LoadShoppingList()
        btnRecalculated_Click(Nothing, Nothing)
        Try
            lblConsolidationText.Text = ConPointService.GetConPoint(ShoppingConext.ShopingSelectedConsolidation).Description
        Catch ex As Exception
            lblConsolidationText.Text = "[None selection]"
        End Try
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        AddHandler dlShoppingList.ItemDataBound, AddressOf dlShoppingList_ItemDataBound

        If (Not IsPostBack) Then
            ' ReferrerUrl = Utilities.GetReferrerUrl("ShippingForm.aspx")
            ' Setup country selection list
            Dim list As New ListItemCollection
            Dim UK_ID As String = ""
            If (Not Countries Is Nothing AndAlso Countries.Count > 0) Then
                For Each item As Country In Countries
                    Dim roadWeigth1 As Decimal = item.RoadWeight
                    Dim roadWeightStr As String = "unknown"
                    If (roadWeigth1 <> Nulls.NullDecimal) Then
                        Dim roadWeight As Decimal = Convert.ToDecimal(IIf(item.MeasUnit = "Metric", item.RoadWeight, item.RoadWeight * Convert.ToDecimal(ONE_KG_TO_LBS)))
                        roadWeightStr = Math.Round(roadWeight).ToString(Config.NumericFormat)
                        'roadWeightStr = item.RoadWeight.ToString()
                    End If
                    Dim name As String = String.Format("{0} - Allowable road weight: {1} ({2})", item.CountryName, roadWeightStr, Convert.ToString(IIf(item.MeasUnit = "Metric", "kg", "lbs")))
                    list.Add(New ListItem(name, item.CountryID.ToString()))
                    If (item.CountryCode = "UK" OrElse item.CountryName = "United Kingdom") Then
                        UK_ID = item.CountryID.ToString()
                    End If
                Next
                ddlCountry.DataSource = list
                ddlCountry.DataBind()

                If (Not RequestContext.CurrentUser Is Nothing AndAlso RequestContext.CurrentUser.IS_ADMIN AndAlso RequestContext.CurrentDestinationCountry = 0) Then
                    Try
                        ddlCountry.Items.FindByValue(UK_ID).Selected = True
                    Catch ex As Exception
                        ddlCountry.SelectedIndex = 0
                    End Try
                    ddlCountry_OnSelectedIndexChanged(Nothing, Nothing)
                    LoadRoadWeightAndUnit() ' not change position of this code line
                    'hidMeasUnit.Value = "cbm" 'Make Admin default to Metric
                Else
                    Try
                        ddlCountry.Items.FindByValue(RequestContext.CurrentDestinationCountry.ToString()).Selected = True
                    Catch ex As Exception
                        ddlCountry.SelectedIndex = 0
                    End Try
                    ddlCountry_OnSelectedIndexChanged(Nothing, Nothing)
                    LoadRoadWeightAndUnit() ' not change position of this code line
                End If
            Else
                hidMeasUnit.Value = "cbm" 'Make Admin default to Metric
            End If

            ReloadSizeContainer()
            RebindVolumeValues()
            LoadShoppingList()
            LoadTotalValue()
        End If

        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToUpper() = "RELOAD" Then
            GetShoppingListFromDB()
            ReloadSizeContainer()
            RebindVolumeValues()
            LoadShoppingList()
            LoadTotalValue()
            Try
                lblConsolidationText.Text = ConPointService.GetConPoint(ShoppingConext.ShopingSelectedConsolidation).Description
            Catch ex As Exception
                lblConsolidationText.Text = "[None selection]"
            End Try
        End If

        'Highlight AddNote link if there are notes in there to read
        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToUpper() = "REFRESH" Then
            RebindVolumeValues()
            LoadShoppingList()
            LoadTotalValue()
        End If
        hid20C.Value = GetCBMValueByUnitCode("20C").ToString()
        hid40C.Value = GetCBMValueByUnitCode("40C").ToString()
        hid40HC.Value = GetCBMValueByUnitCode("40HC").ToString()

        lblTerritory.Text = Convert.toString(IIf(Session(Constant.SS_TERRITORY) Is Nothing, "", Session(Constant.SS_TERRITORY)))
        lblCountry.Text = Convert.ToString(IIf(Session(Constant.SS_COUNTRY) Is Nothing, "", Session(Constant.SS_COUNTRY)))

        ' For save the shopping list
        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToString = "saveList" Then 'replace existed items
            SaveShoppingList(False)
        End If
        Dim bSaved As Boolean = False
        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToString = "saveListByReplace" Then 'replace existed items
            'Do nothing, just turn on flag b/c it will get current selection to save only
            bSaved = True
        End If
        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToString = "saveListAddMoreItems" Then 'add more to the existed list
            'Get the existing saved list and then merge with the current selection
            RebuildShoppingListForAddItemsToExistingList()
            bSaved = True
        End If
        If (bSaved = True) Then
            SaveShoppingList(True)
        End If

        ShowAccount()
    End Sub

    Private Sub ShowAccount()
        'TODO: hide Con Point link
        loggedInSection.Visible = (ShoppingConext.ShopingUserId > 0)
        divChangeConPoint.Visible = loggedInSection.Visible
        If (ShoppingConext.ShopingUserId > 0) Then
            lblEmail.Text = ShoppingConext.ShopingUserEmail
        End If

        Dim isSavedData As String = ""
        If (ShoppingConext.ShopingUserId > 0) Then
            isSavedData = "1"
        End If
        btnClearSavedList.Attributes.Add("onclick", String.Format("javascript: return ConfirmMessage('{0}');", isSavedData))
    End Sub

    Private Sub RebuildShoppingListForAddItemsToExistingList()
        Dim shoppingOrderCol As ShoppingOrderCollection = ShoppingListService.GetShoppingOrderByShoppingUserId(ShoppingConext.ShopingUserId)
        Dim shoppingOrderItem As New ShoppingOrder
        Dim bExisted As Boolean = False
        Dim oCollection As New Collection

        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        If (Not shoppingOrderCol Is Nothing AndAlso shoppingOrderCol.Count > 0) Then
            For Each item As ShoppingOrder In shoppingOrderCol
                If (ShoppingConext.ShopingSelectedConsolidation = item.ConPointID) Then
                    shoppingOrderItem = item
                    bExisted = True
                    Exit For
                End If
            Next
            If (bExisted) Then 'Load a existing saved list & current selection if have
                Dim previousShoppingList As Collection = LoadShoppingToCurrentSelection(ShoppingConext.ShopingUserId, ShoppingConext.ShopingSelectedConsolidation, shoppingOrderItem)
                If (Not oCollection Is Nothing AndAlso oCollection.Count > 0) Then
                    For i As Integer = 1 To oCollection.Count
                        previousShoppingList.Add(DirectCast(oCollection(i), ShoppingItem))
                    Next
                End If
                Session(Constant.SS_SHOPPING_LIST) = previousShoppingList
            End If
        End If
    End Sub

    Function LoadShoppingToCurrentSelection(ByVal shopingUserId As Integer, ByVal selectedConPoint As Integer, ByVal shoppingOrderItem As ShoppingOrder) As Collection
        Dim shoppingItemsList As ShoppingListCollection = ShoppingListService.GetShoppingListByShoppingUserIdAndConPoint(shopingUserId, selectedConPoint)
        Dim previousShoppingList As New Collection
        If (Not shoppingItemsList Is Nothing AndAlso shoppingItemsList.Count > 0) Then
            Dim item As New shoppingItem
            For Each shoppingItem As ShoppingList In shoppingItemsList
                item = New shoppingItem
                With item
                    .ItemNo = shoppingItem.IDSSort
                    .ProductCode = shoppingItem.ProductCode
                    .Description = shoppingItem.Description
                    .Quantity = shoppingItem.Qty
                    .UnitDesc = shoppingItem.UnitSetting
                    Try
                        .UnitSettingID = shoppingItem.UnitSettingID
                    Catch ex As Exception
                    End Try

                    .UnitPrice = shoppingItem.UnitPrice
                    .Total = shoppingItem.TotalPrice
                    .UnitWeight = Convert.ToDecimal(shoppingItem.UnitWeight)
                    .Priority = shoppingItem.PriorityIndex
                    .BulkOrderId = shoppingItem.BulkOrderId
                    .TerritoryID = shoppingItem.TerritoryID
                    .MinQtyVolume = Convert.ToDecimal(shoppingItem.MinQtyVolume)
                    .CountryId = selectedConPoint
                End With
                previousShoppingList.Add(item)
            Next
        End If
        Return previousShoppingList
    End Function

    Private Sub LoadShoppingList()
        'Shopping List
        Dim oCollection As New Collection
        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If

        'If the selected volume > available volume then need to subtract some items from shopping list by update priority value
        Dim shopItem As New ShoppingItem
        Dim dbSelectedTotalVol As Double = 0
        Dim dbAvailableTotalVol As Double = 0
        If (txtTotalVolumeAvailable.Text.Trim.Length > 0) Then
            dbAvailableTotalVol = Convert.ToDouble(txtTotalVolumeAvailable.Text)
        End If
        For i As Integer = 1 To oCollection.Count
            shopItem = DirectCast(oCollection(i), ShoppingItem)

            'Convert to Imperial measurement
            If (IsImperialUnit AndAlso shopItem.IsConvertedToCurrentMeasurementUnit = False) Then
                shopItem.UnitWeight = shopItem.UnitWeight * Convert.ToDecimal(ONE_KG_TO_LBS)
                shopItem.MinQtyVolume = shopItem.MinQtyVolume * Convert.ToDecimal(ONE_VOLUME_CBM_TO_CUFT)
                shopItem.IsConvertedToCurrentMeasurementUnit = True
            End If
            'Revert back from Imperial measurement if any
            If (shopItem.IsConvertedToCurrentMeasurementUnit AndAlso IsImperialUnit = False) Then
                shopItem.UnitWeight = shopItem.UnitWeight / Convert.ToDecimal(ONE_KG_TO_LBS)
                shopItem.MinQtyVolume = shopItem.MinQtyVolume / Convert.ToDecimal(ONE_VOLUME_CBM_TO_CUFT)
                shopItem.IsConvertedToCurrentMeasurementUnit = False
            End If
            dbSelectedTotalVol = dbSelectedTotalVol + (shopItem.Quantity * GetCBMValue(shopItem.UnitSettingID, shopItem.MinQtyVolume))
            If (dbAvailableTotalVol <> 0 AndAlso dbSelectedTotalVol > dbAvailableTotalVol AndAlso shopItem.Priority = 1) Then
                shopItem.Priority = 3
            End If
        Next
        Try
            'SortCollection(oCollection, "ItemNo", True)
            'Sort collection by ProductCode then recalculate Item No field before bind to the list
            SortCollection(oCollection, "ProductCode", True)
            For i As Integer = 1 To oCollection.Count
                shopItem = DirectCast(oCollection(i), ShoppingItem)
                'shopItem.ItemNo = i
            Next
        Catch ex As Exception
        End Try
        Session(Constant.SS_SHOPPING_LIST) = oCollection
        dlShoppingList.DataSource = oCollection
        dlShoppingList.DataBind()
    End Sub

    Protected Function GetQuantityHTML(ByVal test As Object) As String
        Dim oCollection As New Collection
        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        Return "1"
    End Function

    Private Sub dlShoppingList_ItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs)
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            Dim oShoppingItem As ShoppingItem
            oShoppingItem = DirectCast(e.Item.DataItem, ShoppingItem)

            Dim ltrItemIndex As TextBox = CType(e.Item.FindControl("ltrItemIndex"), TextBox)
            ltrItemIndex.Text = (e.Item.ItemIndex + 1).ToString()

            Dim ItemNo As TextBox = CType(e.Item.FindControl("ItemNo"), TextBox)
            'ItemNo.Text = (e.Item.ItemIndex + 1).ToString()
            ItemNo.Text = oShoppingItem.ItemNo.ToString

            Dim txtOrderQty As System.Web.UI.WebControls.TextBox
            txtOrderQty = CType(e.Item.FindControl("OrderQty"), System.Web.UI.WebControls.TextBox)

            txtOrderQty.Text = oShoppingItem.Quantity.ToString

            'Price order
            Dim lblUnitPrice As System.Web.UI.WebControls.TextBox
            lblUnitPrice = CType(e.Item.FindControl("UnitPrice"), System.Web.UI.WebControls.TextBox)
            lblUnitPrice.Text = "$" & oShoppingItem.UnitPrice.ToString(Config.DecimalFormat2)

            'Total
            Dim lblTotal As System.Web.UI.WebControls.TextBox
            lblTotal = CType(e.Item.FindControl("Total"), System.Web.UI.WebControls.TextBox)
            lblTotal.Text = "$" & oShoppingItem.Total.ToString(Config.DecimalFormat2)

            'Priority
            Dim ddlPriority As System.Web.UI.WebControls.DropDownList
            ddlPriority = CType(e.Item.FindControl("ddlPriority"), System.Web.UI.WebControls.DropDownList)
            ddlPriority.SelectedValue = oShoppingItem.Priority.ToString

            'linkAddNote
            Dim linkAddNote As System.Web.UI.HtmlControls.HtmlGenericControl
            linkAddNote = CType(e.Item.FindControl("linkAddNote"), System.Web.UI.HtmlControls.HtmlGenericControl)
            If (Not oShoppingItem.Notes Is Nothing AndAlso oShoppingItem.Notes.Length > 0 AndAlso Not linkAddNote Is Nothing) Then
                linkAddNote.Style.Add("color", "red")
                linkAddNote.InnerText = "Notes"
            End If
        End If

    End Sub

    Protected Sub lnkRemove_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim itemNo As Int16 = Convert.ToInt16(e.CommandArgument)
        Dim iIndex As Integer
        Dim oCollection As New Collection
        Dim orgCount As Integer = 0
        Dim curCount As Integer = 0

        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        If (oCollection.Count > 0) Then
            orgCount = oCollection.Count
            For iIndex = 1 To orgCount
                If (DirectCast(oCollection(iIndex), ShoppingItem).ItemNo = itemNo) Then
                    oCollection.Remove(iIndex)
                    Exit For
                End If
            Next
            ''No need to update ItemNo b/c it's number from IDS screen
            'If (iIndex < orgCount) Then
            '    curCount = oCollection.Count
            '    While (curCount >= iIndex)
            '        DirectCast(oCollection(curCount), ShoppingItem).ItemNo = curCount
            '        curCount = curCount - 1
            '    End While
            '    'For iIndex = iIndex + 1 To oCollection.Count
            '    '    DirectCast(oCollection(iIndex), ShoppingItem).ItemNo = iIndex - 1
            '    'Next
            'End If

            'Sort collection by ProductCode then recalculate Item No field before bind to the list
            Dim shopItem As New ShoppingItem
            'SortCollection(oCollection, "ProductCode", True)
            SortCollection(oCollection, "ItemNo", True)
            ''No need to update ItemNo b/c it's number from IDS screen
            'For i As Integer = 1 To oCollection.Count
            '    shopItem = DirectCast(oCollection(i), ShoppingItem)
            '    shopItem.ItemNo = i
            'Next

            Session(Constant.SS_SHOPPING_LIST) = oCollection

            dlShoppingList.DataSource = oCollection
            dlShoppingList.DataBind()
            LoadTotalValue()
        End If
    End Sub

    Private Sub btnRecalculated_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecalculated.Click
        Dim lblTotal As System.Web.UI.WebControls.TextBox
        Dim lblUnitPrice As System.Web.UI.WebControls.TextBox
        Dim txtOrderQty As System.Web.UI.WebControls.TextBox
        Dim dbTotal As Double = 0
        Dim iIndex As Integer = 0
        Dim oCollection As New Collection
        Dim ddlPriority As System.Web.UI.WebControls.DropDownList
        Dim dbTotalPrice As Double = 0

        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If

        For Each item As DataListItem In dlShoppingList.Items
            iIndex = iIndex + 1
            txtOrderQty = CType(item.FindControl("OrderQty"), System.Web.UI.WebControls.TextBox)
            lblTotal = CType(item.FindControl("Total"), System.Web.UI.WebControls.TextBox)
            lblUnitPrice = CType(item.FindControl("UnitPrice"), System.Web.UI.WebControls.TextBox)

            If (txtOrderQty.Text.Length > 0 AndAlso lblUnitPrice.Text.Length > 0) Then
                'lblTotal.Text = "$" & (minOrderQtyValue * Convert.ToInt16(txtOrderQty.Text) * Convert.ToDouble(lblUnitPrice.Text.Replace("$", ""))).ToString(Config.DecimalFormat2)
                dbTotalPrice = (Convert.ToInt16(txtOrderQty.Text) * Convert.ToDouble(lblUnitPrice.Text.Replace("$", "")))
            End If

            ddlPriority = CType(item.FindControl("ddlPriority"), System.Web.UI.WebControls.DropDownList)

            'update changes back to session
            Dim minOrderQtyValue As Integer = 1

            With DirectCast(oCollection(iIndex), ShoppingItem)
                ''No need to update ItemNo b/c it's number from IDS screen
                '.ItemNo = iIndex
                If (txtOrderQty.Text.Length > 0) Then
                    .Quantity = Convert.ToInt16(txtOrderQty.Text)
                Else
                    .Quantity = 0
                End If
                If (.MinOrderQtyValue > 0) Then
                    minOrderQtyValue = .MinOrderQtyValue
                End If
                If (lblTotal.Text.Trim.Length > 0) Then
                    '.Total = Convert.ToDouble(lblTotal.Text.Replace("$", ""))
                    .Total = dbTotalPrice * minOrderQtyValue
                Else
                    .Total = 0
                End If
                .Priority = Convert.ToInt16(ddlPriority.SelectedValue)
            End With

            lblTotal.Text = "$" & DirectCast(oCollection(iIndex), ShoppingItem).Total.ToString(Config.DecimalFormat2)

            If (lblTotal.Text.Trim.Length > 0) Then
                dbTotal += DirectCast(oCollection(iIndex), ShoppingItem).Total
            End If

        Next

        Session(Constant.SS_SHOPPING_LIST) = oCollection
        ' txtTotalPrice.Text = "$" & dbTotal.ToString

        'Rebind volume
        RebindVolumeValues()

        LoadTotalValue()

        dlShoppingList.DataSource = oCollection
        dlShoppingList.DataBind()
    End Sub

    Private Sub btnProceedOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProceedOrder.Click
        'Dim txtOrderQty As System.Web.UI.WebControls.TextBox
        'Dim i As Integer = 1
        'For Each item As DataListItem In dlShoppingList.Items
        '    txtOrderQty = CType(item.FindControl("OrderQty"), System.Web.UI.WebControls.TextBox)
        'Next
        Dim orderNo As String = ""
        Dim totalVolumeAvailable As String = ""
        Dim totalVolumeSelected As String = ""
        Dim totalGoodWeight As String = ""
        Dim totalPrice As String = ""
        If (rdPartOrder.Checked = True) Then
            orderNo = txtOrderNo.Text.Trim
        Else
            totalVolumeAvailable = txtTotalVolumeAvailable.Text.Trim
            totalVolumeSelected = txtSelectVolumeTotal.Text.Trim
            totalGoodWeight = txtTotalGoodWeight.Text.Trim
            totalPrice = txtTotalPrice.Text.Trim
        End If
        UpdateSizeContainer()
        Response.Redirect(String.Format("ShippingForm.aspx?orderNo={0}&totalVolAvail={1}&totalVolSel={2}&totalGoodWeight={3}&totalPrice={4}&unitType={5}&measUnit={6}", orderNo, totalVolumeAvailable, totalVolumeSelected, totalGoodWeight, totalPrice, hidMeasUnit.Value.Trim, GetMeasUnit()))
    End Sub

    Private Sub btnBackToIDS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackToIDS.Click
        UpdateSizeContainer()
        Response.Redirect(IMStockReportURL())
    End Sub

    Private Sub lnkBackToIDS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkBackToIDS.Click
        UpdateSizeContainer()
        Response.Redirect(IMStockReportURL())
    End Sub

    Private Sub btnSaveYourList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveYourList.Click
        If (ShoppingConext.ShopingUserId = 0) Then
            Page.RegisterStartupScript("newDialog", "<script language='javascript'> openCreateShoppingUserDialog();</script>")
        Else
            Dim conPointID As String = ""
            Try
                conPointID = Convert.ToString(ShoppingConext.ShopingSelectedConsolidation)
            Catch ex As Exception
                conPointID = ""
            End Try
            If (conPointID.Length > 0 AndAlso conPointID <> "0") Then
                Dim shoppingOrderCol As ShoppingOrderCollection = ShoppingListService.GetShoppingOrderByShoppingUserId(ShoppingConext.ShopingUserId)
                Dim shoppingOrder As New shoppingOrder
                Dim bExisted As Boolean = False
                If (Not shoppingOrderCol Is Nothing AndAlso shoppingOrderCol.Count > 0) Then
                    For Each item As shoppingOrder In shoppingOrderCol
                        If (conPointID = item.ConPointID.ToString()) Then
                            shoppingOrder = item
                            bExisted = True
                            Exit For
                        End If
                    Next
                End If
                If (bExisted) Then
                    If Not (Not Session(ShoppingConext.ShopingSelectedConsolidation.ToString()) Is Nothing AndAlso Convert.ToBoolean(Session(ShoppingConext.ShopingSelectedConsolidation.ToString()))) Then
                        Page.RegisterStartupScript("newDialog", String.Format("<script language='javascript'> openConfirmToOverwriteOrAddToExistedListDialog('{0}','{1}','{2}');</script>", conPointID, ShoppingConext.ShopingUserId, ShoppingConext.ShopingUserEmail))
                    End If
                Else
                    SaveShoppingList(False) ' insert new one for con point
                End If
            End If
        End If
    End Sub

    Private Sub btnClearSavedList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearSavedList.Click
        DeleteShoppingList()
    End Sub

    Private Sub lnkNotUseSignedInAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkNotUseSignedInAccount.Click
        ShoppingConext.ShopingUserId = 0
        ShoppingConext.ShopingUserEmail = ""
        ShowAccount()
    End Sub

    Private Sub GetShoppingListFromDB()
        'TODO
        'Dim shopingUserId As Integer = ShoppingConext.ShopingUserId
        'If (shopingUserId > 0) Then
        '    Session(Constant.SS_SHOPPING_LIST) = Nothing
        '    Session(Constant.SS_CONPOINT_ID) = Nothing
        '    Dim shoppingItemsList As ShoppingListCollection = ShoppingListService.GetShoppingListByShoppingUserId(shopingUserId, ShoppingConext.ShopingSelectedConsolidation)
        '    Dim shoppingOrderItem As ShoppingOrder = ShoppingListService.GetShoppingOrderByShoppingUserId(shopingUserId)

        '    Session(Constant.SS_SELECTED_CONPOINT_ID) = shoppingOrderItem.ConPointID
        '    Session(Constant.SS_CONPOINT_ID) = Session(Constant.SS_SELECTED_CONPOINT_ID)

        '    If (Not shoppingOrderItem Is Nothing) Then
        '        Session("txtQty20Cont") = shoppingOrderItem.Qty20
        '        Session("txtQty40Cont") = shoppingOrderItem.Qty40
        '        Session("txtQty40HiCube") = shoppingOrderItem.Qty40HC

        '        Session("txtOrderNo") = shoppingOrderItem.OrderNo
        '        Session("txtHalfPallet") = shoppingOrderItem.HalfPalletSpaces
        '        Session("txtExistingOrderVolume") = shoppingOrderItem.FilledVolume

        '        Session("rdPartOrder") = shoppingOrderItem.OrderType

        '        Session("ddlCountry") = shoppingOrderItem.DestinationCountryId
        '    End If

        '    Dim previousShoppingList As New Collection
        '    If (Not shoppingItemsList Is Nothing AndAlso shoppingItemsList.Count > 0) Then
        '        Dim item As New shoppingItem
        '        For Each shoppingItem As ShoppingList In shoppingItemsList
        '            item = New shoppingItem
        '            With item
        '                .ItemNo = shoppingItem.IDSSort
        '                .ProductCode = shoppingItem.ProductCode
        '                .Description = shoppingItem.Description
        '                .Quantity = shoppingItem.Qty
        '                .UnitDesc = shoppingItem.UnitSetting
        '                Try
        '                    .UnitSettingID = shoppingItem.UnitSettingID
        '                Catch ex As Exception
        '                End Try

        '                .UnitPrice = shoppingItem.UnitPrice
        '                .Total = shoppingItem.TotalPrice
        '                .UnitWeight = Convert.ToDecimal(shoppingItem.UnitWeight)
        '                .Priority = shoppingItem.PriorityIndex
        '                .BulkOrderId = shoppingItem.BulkOrderId
        '                .TerritoryID = shoppingItem.TerritoryID
        '                .MinQtyVolume = Convert.ToDecimal(shoppingItem.MinQtyVolume)
        '                .CountryId = shoppingOrderItem.ConPointID
        '            End With
        '            previousShoppingList.Add(item)
        '        Next
        '        Session(Constant.SS_SHOPPING_LIST) = previousShoppingList
        '    End If
        'End If
    End Sub

    Private Sub SaveShoppingList(ByVal bReplaced As Boolean)

        btnRecalculated_Click(btnRecalculated, Nothing)

        Dim shoppingCartList As New ShoppingListCollection
        'Shopping List
        Dim oCollection As New Collection
        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        Dim shopItem As ShoppingItem
        Dim shoppingItemDB As New ShoppingList
        If (Not oCollection Is Nothing AndAlso oCollection.Count > 0) Then
            For i As Integer = 1 To oCollection.Count
                shopItem = DirectCast(oCollection(i), ShoppingItem)
                shoppingItemDB = New ShoppingList
                shoppingItemDB.IDSSort = i 'shopItem.ItemNo
                shoppingItemDB.ProductCode = shopItem.ProductCode
                shoppingItemDB.Description = shopItem.Description
                shoppingItemDB.Qty = shopItem.Quantity
                shoppingItemDB.UnitSetting = shopItem.UnitDesc
                shoppingItemDB.UnitPrice = Convert.ToDecimal(shopItem.UnitPrice)
                shoppingItemDB.TotalPrice = Convert.ToDecimal(shopItem.Total)
                shoppingItemDB.PriorityIndex = shopItem.Priority
                shoppingItemDB.Notes = shopItem.Notes
                shoppingItemDB.BulkOrderId = shopItem.BulkOrderId
                shoppingItemDB.UnitSettingID = shopItem.UnitSettingID
                shoppingItemDB.UnitWeight = shopItem.UnitWeight
                shoppingItemDB.MinQtyVolume = shopItem.MinQtyVolume
                shoppingItemDB.TerritoryID = shopItem.TerritoryID
                shoppingCartList.Add(shoppingItemDB)
            Next
        End If

        Dim shoppingOrder As New shoppingOrder
        shoppingOrder.UserId = ShoppingConext.ShopingUserId
        shoppingOrder.OrderType = rdFullContainer.Checked '1: for a full container of goods all selected from the IDS ; 0 : Forms part of a existing production order 
        If (rdFullContainer.Checked) Then
            Try
                shoppingOrder.Qty20 = Convert.ToInt32(IIf(txtQty20Cont.Text.Trim() > "", txtQty20Cont.Text.Trim(), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.Qty40 = Convert.ToInt32(IIf(txtQty40Cont.Text.Trim() > "", txtQty40Cont.Text.Trim(), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.Qty40HC = Convert.ToInt32(IIf(txtQty40HiCube.Text.Trim() > "", txtQty40HiCube.Text.Trim(), 0))
            Catch ex As Exception
            End Try

        Else
            shoppingOrder.OrderNo = txtOrderNo.Text.Trim
            Try
                shoppingOrder.HalfPalletSpaces = Convert.ToDecimal(IIf(txtHalfPallet.Text.Trim() > "", txtHalfPallet.Text.Trim(), 0))
            Catch ex As Exception
            End Try
            Try
                shoppingOrder.FilledVolume = Convert.ToDecimal(IIf(txtExistingOrderVolume.Text.Trim() > "", txtExistingOrderVolume.Text.Trim(), 0))
            Catch ex As Exception
            End Try
        End If
        Try
            shoppingOrder.DestinationCountryId = Convert.ToInt32(ddlCountry.SelectedValue)
        Catch ex As Exception
        End Try
        Try
            shoppingOrder.ConPointID = ShoppingConext.ShopingSelectedConsolidation
        Catch ex As Exception
        End Try
        If (ShoppingConext.ShoppingOrderId > 0) Then
            shoppingOrder.ShoppingOrderId = ShoppingConext.ShoppingOrderId
        End If

        'If (bReplaced) Then
        '    'update existing list
        '    ShoppingListService.CreateShoppingOrderListToExistedList(shoppingCartList, shoppingOrder, ShoppingConext.ShopingUserId, Nulls.NullInteger)
        'Else
        '    'Insert new list for new CoinPoint
        '    ShoppingListService.CreateShoppingCartList(shoppingCartList, shoppingOrder, ShoppingConext.ShopingUserId, Nulls.NullInteger)
        'End If

        ShoppingListService.CreateShoppingCartList(shoppingCartList, shoppingOrder, ShoppingConext.ShopingUserId, Nulls.NullInteger)

        If ((Not shoppingCartList Is Nothing AndAlso shoppingCartList.Count = 0) OrElse shoppingCartList Is Nothing) Then
            System.Web.HttpContext.Current.Session(Constant.SS_SELECTED_CONPOINT_ID) = Nothing
            Session(Constant.SS_SHOPPING_LIST) = Nothing
        End If
        Session(ShoppingConext.ShopingSelectedConsolidation.ToString()) = True
        Page.RegisterStartupScript("az", "<script language='javascript'>alert('Save successfully!');</script>")

    End Sub

    Private Sub DeleteShoppingList()
        ShoppingListService.DeleteShoppingOrderList(ShoppingConext.ShopingUserId, ShoppingConext.ShopingSelectedConsolidation)
        ClearShoppingCartData()
        Page.RegisterStartupScript("az1", "<script language='javascript'>alert('List deleted successfully!');</script>")
        Response.Redirect(IMStockReportURL())
    End Sub

    Private Sub ClearShoppingCartData()
        Session(Constant.SS_SHOPPING_LIST) = Nothing ' clear shopping list
        Session(Constant.txtExistingOrderVolume) = Nothing ' clear shopping list
        Session(Constant.txtHalfPallet) = Nothing ' clear shopping list
        Session(Constant.txtOrderNo) = Nothing ' clear shopping list
        Session(Constant.txtQty20Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40HiCube) = Nothing ' clear shopping list
        Session(Constant.rdPartOrder) = Nothing ' clear shopping list
        Session(Constant.ddlCountry) = Nothing ' clear shopping list
        RequestContext.CurrentDestinationCountry = Nothing
        Session(Constant.SS_CONPOINT_ID) = Nothing
        Session(ShoppingConext.ShopingSelectedConsolidation.ToString()) = Nothing
        Session(Constant.SS_SELECTED_CONPOINT_ID) = Nothing
    End Sub

    Protected Property ReferrerUrl() As String
        Get
            Return Convert.ToString(ViewState("ReferrerUrl"))
        End Get
        Set(ByVal Value As String)
            ViewState("ReferrerUrl") = Value
        End Set

    End Property

    Private Sub RebindVolumeValues()
        Dim dVolume20, dVolume40, dVolume40HiCube, total, totalWeight As Double
        total = 0
        totalWeight = 0
        If hidMeasUnit.Value = "cu ft" Then
            dVolume20 = 30 * ONE_VOLUME_CBM_TO_CUFT '35 * ONE_VOLUME_CBM_TO_CUFT
            dVolume40 = 60 * ONE_VOLUME_CBM_TO_CUFT '70 * ONE_VOLUME_CBM_TO_CUFT
            dVolume40HiCube = 76 * ONE_VOLUME_CBM_TO_CUFT '80 * ONE_VOLUME_CBM_TO_CUFT

        ElseIf (hidMeasUnit.Value = "cbm") Then
            dVolume20 = GetCBMValueByUnitCode("20C")
            dVolume40 = GetCBMValueByUnitCode("40C")
            dVolume40HiCube = GetCBMValueByUnitCode("40HC")
        Else
            dVolume20 = 30
            dVolume40 = 60
            dVolume40HiCube = 76
        End If

        If (txtQty20Cont.Text.Trim.Length > 0) Then
            txtVolumeUnit20.Text = (Convert.ToInt16(txtQty20Cont.Text) * dVolume20).ToString
        Else
            txtVolumeUnit20.Text = ""
        End If
        If (txtQty40Cont.Text.Trim.Length > 0) Then
            txtVolumeUnit40.Text = (Convert.ToInt16(txtQty40Cont.Text) * dVolume40).ToString
        Else
            txtVolumeUnit40.Text = ""
        End If
        If (txtQty40HiCube.Text.Trim.Length > 0) Then
            txtVolumeUnit40HiCube.Text = (Convert.ToInt16(txtQty40HiCube.Text) * dVolume40HiCube).ToString
        Else
            txtVolumeUnit40HiCube.Text = ""
        End If
        If (txtQty20Cont.Text.Trim.Length > 0) Then
            total = Convert.ToDouble(txtVolumeUnit20.Text)

            totalWeight = Convert.ToDouble(txtQty20Cont.Text) * RoadWeight
        End If
        If (txtQty40Cont.Text.Trim.Length > 0) Then
            total = total + Convert.ToDouble(txtVolumeUnit40.Text)

            totalWeight = totalWeight + Convert.ToDouble(txtQty40Cont.Text) * RoadWeight
        End If
        If (txtVolumeUnit40HiCube.Text.Trim.Length > 0) Then
            total = total + Convert.ToDouble(txtVolumeUnit40HiCube.Text)

            totalWeight = totalWeight + Convert.ToDouble(txtQty40HiCube.Text) * RoadWeight
        End If

        If (total <> 0) Then
            txtTotalVolumeAvailable.Text = total.ToString
        Else
            txtTotalVolumeAvailable.Text = ""
        End If

        If (totalWeight <> 0) Then
            txtTotalWeightAvailable.Text = Math.Round(totalWeight).ToString()
        Else
            txtTotalWeightAvailable.Text = ""
        End If
    End Sub

    Private Sub LoadTotalValue()
        Dim lblTotal As System.Web.UI.WebControls.TextBox
        Dim txtOrderQty As System.Web.UI.WebControls.TextBox
        Dim dbTotal As Double = 0
        Dim dbSelectedTotalVol As Double = 0
        Dim dbTotalGoodWeight As Double = 0
        Dim shopItem As New ShoppingItem

        'Shopping List
        Dim oCollection As New Collection
        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
        End If

        Dim ddlPriority As System.Web.UI.WebControls.DropDownList
        For Each item As DataListItem In dlShoppingList.Items
            lblTotal = CType(item.FindControl("Total"), System.Web.UI.WebControls.TextBox)
            ddlPriority = CType(item.FindControl("ddlPriority"), System.Web.UI.WebControls.DropDownList)
            'Just calculate total for Priority "Increase"
            If (lblTotal.Text.Trim.Length > 0 AndAlso (ddlPriority.SelectedValue = "1" OrElse ddlPriority.SelectedValue = "-1" OrElse ddlPriority.SelectedValue = "2")) Then
                dbTotal += Convert.ToDouble(lblTotal.Text.Replace("$", ""))
            End If
        Next

        For i As Integer = 1 To oCollection.Count
            shopItem = DirectCast(oCollection(i), ShoppingItem)
            'Just calculate total for Priority "--select--"/"Increase"/"Exact"
            If (shopItem.Priority = -1 OrElse shopItem.Priority = 0 OrElse shopItem.Priority = 1 OrElse shopItem.Priority = 2) Then
                dbSelectedTotalVol = dbSelectedTotalVol + (shopItem.Quantity * GetCBMValue(shopItem.UnitSettingID, shopItem.MinQtyVolume))
            End If
            'Just calculate weight total for Priority "--select--"/"Increase"/"Exact"
            If (shopItem.Priority = -1 OrElse shopItem.Priority = 0 OrElse shopItem.Priority = 1 OrElse shopItem.Priority = 2) Then
                dbTotalGoodWeight = dbTotalGoodWeight + (shopItem.Quantity * shopItem.UnitWeight)
            End If
        Next

        'Total XXX Value
        txtTotalPrice.Text = "$" & dbTotal.ToString(Config.DecimalFormat2)

        '==========================================================================
        '% Full for Total Volume Selected
        'Note: already convert to appropriate value in shopItem.UnitWeight & shopItem.MinQtyVolume at LoadShoppingList()
        'If hidMeasUnit.Value = "cu ft" Then
        '    dbSelectedTotalVol = dbSelectedTotalVol * ONE_VOLUME_CBM_TO_CUFT
        'End If

        'Total Volume Selected
        If (dbSelectedTotalVol = 0) Then
            txtSelectVolumeTotal.Text = "0"
        Else
            txtSelectVolumeTotal.Text = dbSelectedTotalVol.ToString(Config.DecimalFormat)
        End If

        '% volume 
        Dim dbTotalVolumeAvailable As Double = 0
        If (rdPartOrder.Checked) Then
            If (radHalfPallet.Checked = False) Then
                If (txtExistingOrderVolume.Text.Length > 0 AndAlso Convert.ToDouble(txtExistingOrderVolume.Text) > 0) Then
                    dbTotalVolumeAvailable = Convert.ToDouble(txtExistingOrderVolume.Text)
                End If
            Else
                If (txtHalfPallet.Text.Length > 0 AndAlso Convert.ToDouble(txtHalfPallet.Text) > 0) Then
                    dbTotalVolumeAvailable = (Convert.ToDouble(txtHalfPallet.Text) * GetCBMValueByUnitCode("4HDP"))
                End If
            End If
        Else
            If (txtTotalVolumeAvailable.Text.Length > 0 AndAlso Convert.ToDouble(txtTotalVolumeAvailable.Text) > 0) Then
                dbTotalVolumeAvailable = Convert.ToDouble(txtTotalVolumeAvailable.Text)
            End If
        End If

        If (dbTotalVolumeAvailable = 0) Then
            txtPercentFull.Text = ""
        Else
            If ((dbSelectedTotalVol / (dbTotalVolumeAvailable)) = 0) Then
                txtPercentFull.Text = "0"
            Else
                txtPercentFull.Text = ((dbSelectedTotalVol / dbTotalVolumeAvailable) * 100).ToString(Config.DecimalFormat)
            End If
        End If

        'Remaining volume 
        If ((dbTotalVolumeAvailable - dbSelectedTotalVol) = 0) Then
            txtRemainVolume.Text = "0"
        Else
            Dim result As String = (dbTotalVolumeAvailable - dbSelectedTotalVol).ToString(Config.DecimalFormat)
            If (result.IndexOf("-.") = 0) Then
                txtRemainVolume.Text = result.Replace("-", "-0")
            Else
                txtRemainVolume.Text = result
            End If
        End If

        If (rdPartOrder.Checked) Then
            If (radHalfPallet.Checked) Then
                'Calculate Remaining volume  by select Part Order option. Unit Code 4HDP = Half Pallets
                If (txtHalfPallet.Text.Trim().Length < 0 OrElse txtHalfPallet.Text = "") Then
                    txtRemainVolume.Text = "0"
                Else
                    Try
                        'Andy:  Total Volume Selected, % Full (Volume) and Total Weight of Goods selected should still be calculated 
                        'based on the Remaining volume. It is just these 3 fields that need to work. 
                        ' The same 3 fields work OK when when the volume is entered directly.
                        If ((dbSelectedTotalVol / (dbTotalVolumeAvailable)) = 0) Then
                            txtPercentFull.Text = "0"
                        Else
                            txtPercentFull.Text = ((dbSelectedTotalVol / dbTotalVolumeAvailable) * 100).ToString(Config.DecimalFormat)
                        End If
                    Catch ex As Exception
                    End Try
                End If
            End If
        End If

        'Change color
        Try
            If (Convert.ToDecimal(txtRemainVolume.Text) < 0) Then
                txtSelectVolumeTotal.ForeColor = System.Drawing.Color.Red
                txtPercentFull.ForeColor = System.Drawing.Color.Red
                txtRemainVolume.ForeColor = System.Drawing.Color.Red
            Else
                txtSelectVolumeTotal.ForeColor = System.Drawing.Color.Black
                txtPercentFull.ForeColor = System.Drawing.Color.Black
                txtRemainVolume.ForeColor = System.Drawing.Color.Black
            End If
        Catch ex As Exception
            txtRemainVolume.ForeColor = System.Drawing.Color.Black
        End Try

        ''Change color
        'If (rdPartOrder.Checked) Then
        '    If (radHalfPallet.Checked) Then
        '        Try
        '            If (Convert.ToDecimal(txtSelectVolumeTotal.Text) < 0) Then
        '                txtSelectVolumeTotal.ForeColor = System.Drawing.Color.Red
        '            Else
        '                txtSelectVolumeTotal.ForeColor = System.Drawing.Color.Black
        '            End If
        '        Catch ex As Exception
        '            txtSelectVolumeTotal.ForeColor = System.Drawing.Color.Black
        '        End Try
        '        Try
        '            If (Convert.ToDecimal(txtPercentFull.Text) < 0) Then
        '                txtPercentFull.ForeColor = System.Drawing.Color.Red
        '            Else
        '                txtPercentFull.ForeColor = System.Drawing.Color.Black
        '            End If
        '        Catch ex As Exception
        '            txtPercentFull.ForeColor = System.Drawing.Color.Black
        '        End Try
        '    End If
        'End If
        '===============================================================================
        'Total good weight
        Dim totalGoodWeight As String = Math.Round(dbTotalGoodWeight).ToString()
        If (totalGoodWeight.IndexOf(".") > 0) Then
            txtTotalGoodWeight.Text = totalGoodWeight.Substring(0, totalGoodWeight.IndexOf("."))
        Else
            txtTotalGoodWeight.Text = totalGoodWeight
        End If

        '% Full for good weight
        'Note: replace this segment code by code line below
        'Dim dbRoadWeight As Double = 0
        'If (Not SelectedCountry Is Nothing AndAlso SelectedCountry.RoadWeight <> Nulls.NullDecimal) Then
        '    dbRoadWeight = SelectedCountry.RoadWeight
        'End If
        'If hidMeasUnit.Value = "cu ft" Then
        '    dbRoadWeight = dbRoadWeight * ONE_KG_TO_LBS
        'End If
        Dim totalWeightAvailable As Double = 0
        Try
            totalWeightAvailable = Convert.ToDouble(txtTotalWeightAvailable.Text)
        Catch ex As Exception
        End Try
        If (totalWeightAvailable = 0) Then
            txtGoodWeightPercentFull.Text = ""
        Else
            txtGoodWeightPercentFull.Text = ((dbTotalGoodWeight / totalWeightAvailable) * 100).ToString(Config.DecimalFormat)
        End If
        'Remaining weight
        If ((totalWeightAvailable - dbTotalGoodWeight) = 0) Then
            txtGoodWeightRemain.Text = "0"
        Else
            Dim goodWeightRemain As String = Math.Round(totalWeightAvailable - dbTotalGoodWeight).ToString()
            If (goodWeightRemain.IndexOf(".") > 0) Then
                txtGoodWeightRemain.Text = goodWeightRemain.Substring(0, goodWeightRemain.IndexOf("."))
            Else
                txtGoodWeightRemain.Text = goodWeightRemain
            End If
        End If
        Try
            If (Convert.ToDecimal(txtGoodWeightRemain.Text) < 0) Then
                txtTotalGoodWeight.ForeColor = System.Drawing.Color.Red
                txtGoodWeightPercentFull.ForeColor = System.Drawing.Color.Red
                txtGoodWeightRemain.ForeColor = System.Drawing.Color.Red
            Else
                txtTotalGoodWeight.ForeColor = System.Drawing.Color.Black
                txtGoodWeightPercentFull.ForeColor = System.Drawing.Color.Black
                txtGoodWeightRemain.ForeColor = System.Drawing.Color.Black
            End If
        Catch ex As Exception
            txtGoodWeightRemain.ForeColor = System.Drawing.Color.Black
        End Try
        If (rdPartOrder.Checked) Then
            txtTotalGoodWeight.ForeColor = System.Drawing.Color.Black
        End If
    End Sub

    Protected Function GetRowClass(ByVal container As Object) As String
        Dim item As DataListItem = CType(container, DataListItem)

        If item.ItemIndex Mod 2 = 0 Then
            Return "ItemRow"
        Else
            Return "AlternateItemRow"
        End If

    End Function

    Protected Function GetFOBorHDHeader() As String
        If (Session("FOBorHD") Is Nothing) Then
            Return ""
        Else
            Return CType(Session("FOBorHD"), String)
        End If
    End Function

    Protected Function GetPackType2Text(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackType2Meaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetIMStockReportURL() As String
        Return String.Format("<a href={0} > Back to IDS </a>", IMStockReportURL())
    End Function

    Private Function IMStockReportURL() As String
        Dim strURL As String = "IMStockReport.aspx?discount={4}&dorpt=1&teid={2}&ownerid=-2&showfob={5}&cpid={0}&qty={1}&sort={3}&countryid={6}"
        Dim result As String = "IMStockReport.aspx?dorpt=1&teid=-1&ownerid=-2&showfob=1&cpid=0"
        Dim params As New Common.IMStockReportParams

        If Not Session("IMStockReportParams") Is Nothing Then
            params = DirectCast(Session("IMStockReportParams"), Common.IMStockReportParams)
            Dim showfob As Integer = 0
            If (params.Showfob) Then
                showfob = 1
            End If
            result = String.Format(strURL, params.ConPointID, params.Quantity, params.TerritoryId, params.IDSSort, params.Discount, showfob, params.CountryId)
        End If
        Return result
    End Function

    Protected Function GetMeasUnit() As String
        If hidMeasUnit.Value = "cu ft" Then
            Return "lbs"
        Else
            Return "kg"
        End If
    End Function

    Private Sub UpdateSizeContainer()
        Session("txtQty20Cont") = txtQty20Cont.Text
        Session("txtQty40Cont") = txtQty40Cont.Text
        Session("txtQty40HiCube") = txtQty40HiCube.Text

        Session("txtOrderNo") = txtOrderNo.Text.Trim
        Session("txtHalfPallet") = txtHalfPallet.Text.Trim
        Session("txtExistingOrderVolume") = txtExistingOrderVolume.Text.Trim

        Session("rdPartOrder") = rdPartOrder.Checked
        Try
            Session("ddlCountry") = ddlCountry.SelectedValue
        Catch ex As Exception
        End Try
    End Sub

    Private Sub ReloadSizeContainer()
        txtQty20Cont.Text = CType(IIf(Session("txtQty20Cont") Is Nothing, "", Session("txtQty20Cont")), String)
        txtQty40Cont.Text = CType(IIf(Session("txtQty40Cont") Is Nothing, "", Session("txtQty40Cont")), String)
        txtQty40HiCube.Text = CType(IIf(Session("txtQty40HiCube") Is Nothing, "", Session("txtQty40HiCube")), String)

        txtOrderNo.Text = CType(IIf(Session("txtOrderNo") Is Nothing, "", Session("txtOrderNo")), String)
        txtHalfPallet.Text = CType(IIf(Session("txtHalfPallet") Is Nothing, "", Session("txtHalfPallet")), String)
        txtExistingOrderVolume.Text = CType(IIf(Session("txtExistingOrderVolume") Is Nothing, "", Session("txtExistingOrderVolume")), String)

        'rdPartOrder.Checked = CType(IIf(Session("rdPartOrder") Is Nothing, False, Session("rdPartOrder")), Boolean)
        'txtGoodWeightPercentFull.Visible = rdPartOrder.Checked
        'txtGoodWeightRemain.Visible = rdPartOrder.Checked

        Try
            If (Not Session("ddlCountry") Is Nothing) Then
                ddlCountry.SelectedValue = Convert.ToString(Session("ddlCountry"))
            End If
        Catch ex As Exception
        End Try
    End Sub

    'Todo review later
    Protected Function GetProductCodeOrder(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return ""
        Else
            Return (Convert.ToString(data))
        End If
    End Function

    Public Sub SortCollection(ByVal col As Collection, _
    ByVal psSortPropertyName As String, ByVal pbAscending As Boolean, _
    Optional ByVal psKeyPropertyName As String = "")

        Dim obj As Object
        Dim i As Integer
        Dim j As Integer
        Dim iMinMaxIndex As Integer
        Dim vMinMax As Object
        Dim vValue As Object
        Dim bSortCondition As Boolean
        Dim bUseKey As Boolean
        Dim sKey As String

        bUseKey = (psKeyPropertyName <> "")

        For i = 1 To col.Count - 1
            obj = col(i)
            ' the vbGet can be replaced with a 
            'CallType.Get if you
            ' want. See VB Language reference for CallByName

            vMinMax = CallByName(obj, psSortPropertyName, vbGet)
            iMinMaxIndex = i

            For j = i + 1 To col.Count
                obj = col(j)
                vValue = CallByName(obj, _
                 psSortPropertyName, vbGet)

                If (pbAscending) Then
                    bSortCondition = (Convert.ToInt32(vValue) < Convert.ToInt32(vMinMax))
                Else
                    bSortCondition = (Convert.ToInt32(vValue) > Convert.ToInt32(vMinMax))
                End If

                If (bSortCondition) Then
                    vMinMax = vValue
                    iMinMaxIndex = j
                End If

                obj = Nothing
            Next j

            If (iMinMaxIndex <> i) Then
                obj = col(iMinMaxIndex)

                col.Remove(iMinMaxIndex)
                If (bUseKey) Then
                    sKey = CStr(CallByName(obj, _
                       psKeyPropertyName, vbGet))
                    col.Add(obj, sKey, i)
                Else
                    col.Add(obj, , i)
                End If

                obj = Nothing
            End If

            obj = Nothing
        Next i

    End Sub

    Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
        UpdateSizeContainer()

        Dim text As String = GetFOBorHDHeader()
        If (text.Trim.Length > 0) Then
            lblToTalValue.Text = String.Format("Total {0} Value:", GetFOBorHDHeader())
        Else
            lblToTalValue.Text = "Total Value:"
        End If
    End Sub

    Protected Function GetUnitWeightHTML(ByVal container As Object) As String
        Dim item As ShoppingItem = CType(container, ShoppingItem)
        Try
            If (item.UnitWeight <> Nulls.NullDecimal) Then
                If (item.UnitWeight = 0D) Then
                    Return "0"
                Else
                    Dim value As String = "0"
                    Dim decimalValue As Decimal = Math.Round(item.UnitWeight * item.Quantity)
                    If (decimalValue >= 1) Then
                        value = decimalValue.ToString(Config.NumericFormat)
                        If (value.IndexOf(".") > 0) Then
                            value = value.Substring(0, value.IndexOf("."))
                        End If
                    Else
                        value = decimalValue.ToString(Config.DecimalFormat2)
                        If (value.IndexOf(".") = 0) Then
                            value = "0" + value
                        End If
                    End If
                    Return value
                End If
            Else
                Return "&nbsp;"
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try
    End Function

    Protected Function GetMinQtyVolumeHTML(ByVal container As Object) As String
        Dim item As ShoppingItem = CType(container, ShoppingItem)
        Try
            If (item.MinQtyVolume <> Nulls.NullDecimal) Then
                If (item.MinQtyVolume = 0D) Then
                    Return "0.00"
                Else
                    Dim value As String = (item.MinQtyVolume * item.Quantity).ToString(Config.DecimalFormat2)
                    If (value.IndexOf(".") = 0) Then
                        value = "0" + value
                    End If
                    Return value
                End If
            Else
                Return "&nbsp;"
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try
    End Function

    'It's already calculated with selected measurement unit
    Protected ReadOnly Property RoadWeight() As Decimal
        Get
            Dim result As Decimal = 0
            If (hidRoadWeight.Value.Trim <> "") Then
                Try
                    result = Decimal.Parse(hidRoadWeight.Value)
                Catch ex As Exception
                End Try
            End If
            Return result
        End Get
    End Property

    Protected ReadOnly Property IsImperialUnit() As Boolean
        Get
            Try
                Return (SelectedCountry.MeasUnit = "Imperial")
            Catch ex As Exception
            End Try
            Return False
        End Get
    End Property

End Class
